package cn.kgc.vue.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.entity.Student;
import cn.kgc.vue.exceptions.BusinessException;
import cn.kgc.vue.mapper.CourseMapper;
import cn.kgc.vue.mapper.StudentMapper;
import cn.kgc.vue.response.ResponseResult;
import cn.kgc.vue.response.ResponseStatus;
import cn.kgc.vue.service.StudentService;
import cn.kgc.vue.vo.StudentVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author mengshun
* @description 针对表【sys_student】的数据库操作Service实现
* @createDate 2024-10-06 08:39:06
*/
@Service
@Transactional
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>implements StudentService{


    @Resource
    private CourseMapper courseMapper;
    @Override
    public ResponseResult studentPage(QueryCondition<Student> queryCondition) {

        Page<Student> studentPage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());
        Student searchParams = queryCondition.getSearchParams();

        LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
        lambda.eq(StringUtils.isNotBlank(searchParams.getStudentNo()),Student::getStudentNo,searchParams.getStudentNo())
                .eq(StringUtils.isNotBlank(searchParams.getClazz()),Student::getClazz,searchParams.getClazz())
                .orderByDesc(Student::getSchoolYear);

        baseMapper.selectPage(studentPage,lambda);

        long total = studentPage.getTotal();
        List<StudentVO> collect = studentPage.getRecords().stream()
                .map(student -> {
                    StudentVO studentVO = new StudentVO();
                    BeanUtils.copyProperties(student, studentVO);
                    Integer courseId = student.getCourseId();
                    String courseName = courseMapper.selectOneCourse(courseId).getCourseName();
                    studentVO.setCourseName(courseName);
                    return studentVO;
                }).collect(Collectors.toList());

        return ResponseResult.success().data("total",total).data("tableData",collect);
    }

    @Override
    public ResponseResult importStudent(List<Student> students) {

        students.forEach(student -> {
            try {
                baseMapper.insert(student);
            }catch (DuplicateKeyException e){
                throw  new BusinessException(ResponseStatus.ERROR.getCode(), student.getStudentNo()+"学号已存在");
            }
        });
        return ResponseResult.success();
    }

    @Override
    public void exportStudents(QueryCondition<Student> queryCondition, HttpServletResponse response) {
        Student searchParams = queryCondition.getSearchParams();
        String studentNo = searchParams.getStudentNo();
        String clazz = searchParams.getClazz();

        LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
        lambda.eq(StringUtils.isNotBlank(studentNo),Student::getStudentNo,studentNo)
                .eq(StringUtils.isNotBlank(clazz),Student::getClazz,clazz);

        // 获取导出的学生信息
        List<Student> students = baseMapper.selectList(lambda);

        // 设置导出参数
        ExportParams exportParams = new ExportParams();
        exportParams.setTitle("学生信息表");
        exportParams.setSheetName("学生信息");
        exportParams.setHeaderColor(HSSFColor.SKY_BLUE.index);

        // 返回工作簿对象
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Student.class, students);

        try {
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}




